new Vue({
    el: "#edit",
    data: {
        addType: 1,
        filterText: "",
        addNode: "",
        startId: null,
        setTree: [], // tree数据
        NODE_KEY: "id", // id对应字段
        MAX_LEVEL: 3, // 设定最大层级
        NODE_ID_START: 0, // 新增节点id，逐次递减
        startId: null,
        defaultProps: {
            // 默认设置
            children: "children",
            label: "value",
            isLeaf: "leaf",
        },
        addDataList: "",
        addForm: {
            name: "",
            key: "",
            id: "",
        },
        addRules: {
            name: [{ required: true, message: "请输入名称", trigger: "blur" }],
            // key: [{ required: true, message: "请输入标签", trigger: "blur" }],
        },
        addDialogTitle: "new",
        addDialogVisible: false,
        // 之前遗忘了这个参数 重新补发
        initParam: {
            // 新增参数
            name: "",
            value: "",
            id: 0,
            children: [],
        },
        editNode: null,
    },
    created() {
        // 初始值
        this.startId = this.NODE_ID_START;
        // lazy
        // :load="loadNode"

        this.init();
    },
    methods: {
        init() {
            this.getAll("select * from clipboard").then((res) => {
                if (res.length > 0) {
                    this.setTree = this.fn(res, 0);
                } else {
                    this.setTree = res;
                }
            });
        },
        send(data) {
            return window.electronAPI.sendMessage(data);
        },
        deepClone(obj) {
            let objClone = Array.isArray(obj) ? [] : {};
            if (obj && typeof obj === "object") {
                for (let key in obj) {
                    if (obj[key] && typeof obj[key] === "object") {
                        objClone[key] = this.deepClone(obj[key]);
                    } else {
                        objClone[key] = obj[key];
                    }
                }
            }
            return objClone;
        },
        fn(result, i) {
            let arr = [];
            result.forEach((v) => {
                if (v.parentId === i) {
                    arr.push(v);
                    v.children = this.fn(result, v.id);
                }
                if (v.children?.length === 0) {
                    delete v.children;
                }
            });
            return arr;
        },
        loadNode(node, resolve) {
            if (node.level == 0) {
                this.getAll(`select * from clipboard where parentId=0`).then(
                    (res) => {
                        res;
                        resolve(res);
                    }
                );
            } else {
                node.data.id;
                this.getAll(
                    `select * from clipboard where parentId=${node.data.id}`
                ).then((res) => {
                    resolve(res);
                });
            }
        },
        /**
         * 在编辑页面初始化数据
         */

        getAll(sql) {
            let channelMsg = {
                type: "store",
                cmd: "sqliteGetAll",
                sql: sql,
            };
            return this.send(channelMsg);
        },
        sqliteEach(sql) {
            let channelMsg = {
                type: "store",
                cmd: "sqliteEach",
                sql: sql,
            };
            this.send(channelMsg);
        },
        sqlliteExecute(sql) {
            let channelMsg = {
                type: "store",
                cmd: "sqlliteExecute",
                sql: sql,
            };
            this.send(channelMsg);
        },
        sqliteInsert(data) {
            let channelMsg = {
                type: "store",
                cmd: "sqliteInsert",
                sql: data["sql"],
                param: data["param"],
            };
            this.send(channelMsg);
        },

        sqliteDelete(sql) {
            this.sqlliteExecute(sql);
        },
        updateDbData(sql) {
            this.getAll(sql);
        },
        sqlliteAdd: function (sql, arr) {
            this.sqliteInsert({ sql: sql, param: arr });
        },

        handleDelete(_node, _data) {
            // 删除节点
            // 判断是否存在子节点
            if (_data.value == "剪切板") {
                this.$message.error("剪切板，不可删除！");
                return false;
            }
            if (_data.children && _data.children.length !== 0) {
                this.$message.error("此节点有子级，不可删除！");
                return false;
            } else {
                // 删除操作
                let DeletOprate = () => {
                    this.$nextTick(() => {
                        if (this.$refs.SlotTree) {
                            this.$refs.SlotTree.remove(_data);
                            this.sqliteDelete(
                                `delete from clipboard where id=${_data.id}`
                            );
                            this.$message.success("删除成功！");
                        }
                    });
                };
                // 二次确认
                let ConfirmFun = () => {
                    this.$confirm("是否删除此节点？", "提示", {
                        confirmButtonText: "确认",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                        .then(() => {
                            DeletOprate();
                        })
                        .catch(() => {});
                };
                // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
                _data[this.NODE_KEY] < this.NODE_ID_START
                    ? DeletOprate()
                    : ConfirmFun();
            }
        },
        back() {
            window.gc();
            window.location.href = "../../index.html";
        },
        handleInput() {
            // 修改节点
            let value = `${this.addForm.key}: ${this.addForm.name}`;
            let key = this.addForm.key;
            this.addDialogVisible = false;

            console.log(value);
            if (!key) {
                value = value.replace(": ", "");
            }
            this.updateDbData(
                `update clipboard set name='${this.addForm.key}', value='${value}' where id=${this.addForm.id}`
            );
            this.editNode.data.name = key;
            this.editNode.data.value = value;
        },
        handleEdit(_node, _data) {
            // 编辑节点

            console.log(_node);
            this.addForm.name = _data.value.replace(`${_data.name}: `, "");

            console.log(this.addForm.name);
            this.addForm.key = _data.name;
            this.addDialogVisible = true;
            this.addDialogTitle = "edit";
            this.addType = 3;
            this.addForm.id = _data.id;
            if (_node.isEdit) {
                this.$set(_node, "isEdit", true);
            }
            this.editNode = _node;
        },
        // 新增子级节点打开事件
        appendChild(node, data) {
            this.addForm.name = "";
            this.addForm.key = "";
            this.addDialogVisible = true;
            this.addDialogTitle = "new";
            this.addDataList = data;
            this.addNode = node;
            this.addType = 2;
        },
        // 新增子级节点
        handleAdd(_node, _data, _obj) {
            // 新增节点
            // 判断层级
            if (_node.level >= this.MAX_LEVEL) {
                this.$message.warning(
                    "当前已达到" + this.MAX_LEVEL + "级，无法新增！"
                );
                return false;
            }
            // 参数修改
            let obj = JSON.parse(JSON.stringify(this.initParam)); // copy参数
            obj.parentId = _data[this.NODE_KEY]; // 父id
            if (_obj.key) {
                obj.value = `${_obj.key}: ${_obj.name}`;
            } else {
                obj.value = _obj.name;
            }
            obj.name = _obj.key;
            // 判断字段是否存在
            if (!_data.children) {
                this.$set(_data, "children", []);
            }
            // 新增数据
            _data.children.push(obj);
            if (obj.value.length > 65535) {
                this.$message.warning("当前文本超过65535长度，无法新增！");
                return;
            }
            this.sqlliteAdd(
                "insert into clipboard (name, value, parentId) values(?, ?, ?)",
                [_obj.key, obj.value, obj.parentId]
            );
            // 展开节点
            if (!_node.expanded) {
                _node.expanded = true;
            }
            //this.init();
        },
        // 新增顶级结点
        handleAddTop() {
            // 添加顶部节点
            let obj = JSON.parse(JSON.stringify(this.initParam)); // copy参数
            //obj[this.NODE_KEY] = ++this.startId; // 节点id：逐次递减id
            if (this.addForm.key) {
                obj.value = `${this.addForm.key}: ${this.addForm.name}`;
            } else {
                obj.value = this.addForm.name;
            }

            obj.name = this.addForm.key;
            this.sqlliteAdd(
                `insert into clipboard (name, value, parentId) values('${obj.name}','${obj.value}', 0)`
            );
            let that = this;
            this.getAll(
                `select * from clipboard where name='${obj.name}' and value='${obj.value}' and parentId=0`
            ).then((res) => {
                console.log(res);
                obj.id = res[0].id;
            });
            this.setTree.push(obj);
            //this.init();
        },

        // 新增顶级结点打开事件
        openAddTop() {
            this.addForm.name = "";
            this.addForm.key = "";
            this.addDialogVisible = true;
            this.addDialogTitle = "new";
            this.addType = 1;
        },
        // 点击确定 新增子级菜单
        addData() {
            var t = this;
            this.$refs.addRef.validate(async (valid) => {
                if (valid) {
                    if (t.addType == 1) {
                        t.handleAddTop();
                        this.addDialogVisible = false;
                    } else if (t.addType == 2) {
                        const obj = JSON.parse(JSON.stringify(t.addForm));
                        // 需要判断新增还是编辑
                        t.handleAdd(t.addNode, t.addDataList, obj);
                        this.addDialogVisible = false;
                    } else if (t.addType == 3) {
                        console.log(`update: ${this.addForm.id}`);
                        t.handleInput();
                    }
                } else {
                    return false;
                }
            });
        },
        addHandleClose() {
            this.addDialogVisible = false;
            this.$refs.addRef.resetFields();
        },
    },
});
